import React, { useState, useRef, useEffect } from 'react'
import Taro, { FC, useRouter, useDidShow, useReachBottom } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { AtTabs, AtTabsPane } from 'taro-ui'
import OrderBtnState from '@/components/OrderBtnState'
import BlankPage from '@/components/BlankPage'
import Payment from '@/components/Payment'
import Modal from '@/components/Modal'
import { OrderDetail } from '@/constants/commonType'
import api from '@/services/config/index'
import { showToast } from '@/utils/common'
import './index.scss'

type OrderList = Array<OrderDetail>
type TabList = Array<{
  title: string
  id: number
}>

interface ConfirmParams {
  type: number | string
  orderId: string
}
const OrderLIst: FC = () => {
  const [current, setCurrent] = useState<number>(0) //当前tab，全部或者待收货或者.....
  const [orderList, setOrderList] = useState<OrderList>([]) //订单列表
  const [showBlankPage, setShowBlankPage] = useState<boolean>(false) //设置空白页
  const [isOpened, setisOpened] = useState<boolean>(false) // 提示弹窗
  const pageNoRef = useRef(1) // 当前页
  const isFinished = useRef(false) //是否加载完
  const pageSizeRef = useRef(5) // 一页多少条

  const tabList = useRef<TabList>([])
  const { params } = useRouter()
  const [showPay, setShowPay] = useState<boolean>(false)
  const orderDetailIndexRef = useRef<number>(0)
  const [modalInfo, setmodalInfo] = useState({
    title: '',
    content: '',
    type: '',
    orderId: ''
  })

  // 获取订单列表，getOrderListIn借入的订单列表，getOrderListOut借出的订单列表
  function getOrderList(type, _current) {
    let url = ''
    if (type === 'orderListIn') {
      url = 'orderList/getOrderListIn'
    } else if (type === 'orderListOut') {
      url = 'orderList/getOrderListOut'
    }
    api[url](
      {
        pageSize: pageSizeRef.current,
        pageNo: pageNoRef.current,
        action: _current
      },
      {
        noShowDefaultError: true,
        noShowLoading: true
      }
    )
      .then((res) => {
        const data = res.data
        if (data.length < pageSizeRef.current) {
          isFinished.current = true
        }
        pageNoRef.current += 1
        setOrderList((pre) => {
          return [...pre, ...data]
        })
      })
      .catch(() => {
        if (pageNoRef.current === 1) {
          setShowBlankPage(true)
        }
        isFinished.current = true
      })
  }

  useDidShow(() => {
    tabClick(current)
  })
  useEffect(() => {
    let title = ''
    if (params.type === 'orderListIn') {
      title = '我借入的物品'
      if (tabList.current.length <= 0) {
        tabList.current = [
          { title: '全部', id: 0 },
          { title: '待支付', id: 1 },
          { title: '待发货', id: 2 },
          { title: '待收货', id: 3 },
          { title: '待归还', id: 4 },
          { title: '归还中', id: 5 },
          { title: '纠纷与评价', id: 6 }
        ]
      }
    } else if (params.type === 'orderListOut') {
      title = '我借出的物品'
      if (tabList.current.length <= 0) {
        tabList.current = [
          { title: '全部', id: 0 },
          { title: '待发货', id: 1 },
          { title: '待收货', id: 2 },
          { title: '待归还', id: 3 },
          { title: '归还中', id: 4 },
          { title: '纠纷与评价', id: 5 }
        ]
      }
    }
    Taro.setNavigationBarTitle({
      title
    })
    setCurrent(Number(params.seq))
  }, [])
  // 上拉加载
  useReachBottom(() => {
    if (!isFinished.current) {
      getOrderList(params.type, current)
    }
  })
  // tab点击
  function tabClick(value) {
    setOrderList([])
    setCurrent(value)
    setShowBlankPage(false)
    isFinished.current = false
    pageNoRef.current = 1
    getOrderList(params.type, value)
  }
  // 取消弹窗
  function onCancel() {
    setisOpened(false)
    if (modalInfo.type === 'orderDispute') {
      api['orderList/orderDispute']({ orderId: modalInfo.orderId, type: 2 }).then(() => {
        showToast('操作成功')
        tabClick(current)
      })
    }
  }
  // 确定按钮
  function onConfirm() {
    setisOpened(false)
    const _params: ConfirmParams = {
      type: '',
      orderId: ''
    }
    const type = modalInfo.type
    let url = ''
    switch (type) {
      case 'orderCancel': // 取消订单
        url = 'orderList/orderCancel'
        break
      case 'deleteOrder': // 删除订单
        url = 'orderList/deleteOrder'
        break
      case 'receiptAction': // 确定收货
        url = 'orderList/receiptAction'
        break
      case 'deliveryAction': // 发货
        url = 'orderList/deliveryAction'
        break
      case 'deliveryReturn': // 归还发货
        url = 'orderList/deliveryReturn'
        break
      case 'receiptReturn': // 归还收货
        url = 'orderList/receiptReturn'
        break
      case 'orderDispute': // 纠纷选择
        _params.type = 1
        url = 'orderList/orderDispute'
        break
    }
    if (!url) return
    _params.orderId = modalInfo.orderId
    api[url](_params).then(() => {
      showToast('操作成功')
      tabClick(current)
    })
  }

  return (
    <View className='orderList com-font-family'>
      <AtTabs
        current={current}
        scroll
        tabList={tabList.current}
        onClick={(e) => {
          tabClick(e)
        }}
      >
        {tabList.current.map((ele, index) => {
          return (
            <AtTabsPane current={current} index={index} key={ele.id}>
              {orderList.length > 0 && (
                <View>
                  {orderList.map((item, key) => {
                    return (
                      <View
                        className='container b-bottom'
                        key={item.orderId}
                        onClick={() => {
                          Taro.navigateTo({
                            url: '/pages/ItemSharing/OrderDetail/index?orderId=' + item.orderId
                          })
                        }}
                      >
                        <View className='orderList-main flex'>
                          <Image
                            src={item.imagePath[0].imagePath}
                            className='orderList-main__img'
                          ></Image>
                          <View className='orderList-main__info'>
                            <View className='orderList-main__info-title font32'>{item.title}</View>
                            <View className='orderList-main__info-cteateTime font24'>
                              创建日期：{item.updateAt}
                            </View>
                            <View className='orderList-main__info-cteateTime font24'>
                              是否需要归还：
                              {item.order.orderIsNeedReturn === '1' ? '需要' : '不需要'}
                            </View>
                            <View className='orderList-main__info-inter font-28'>
                              积分：{item.order.orderTotalPoints}
                            </View>
                          </View>
                        </View>
                        <View className='orderList-btnList flex'>
                          <OrderBtnState
                            orderDetail={item}
                            orderDetailIndex={key}
                            getOrderDetail={() => {
                              tabClick(current)
                            }}
                            openPay={(value) => {
                              orderDetailIndexRef.current = value
                              setShowPay(true)
                            }}
                            // 打开弹窗设置提示内容
                            openModal={(value) => {
                              setmodalInfo(value)
                              setisOpened(true)
                            }}
                          ></OrderBtnState>
                        </View>
                      </View>
                    )
                  })}
                </View>
              )}
              {/* 空白页 */}
              {showBlankPage && <BlankPage></BlankPage>}
            </AtTabsPane>
          )
        })}
      </AtTabs>
      {/* 支付弹窗 */}
      {showPay && (
        <Payment
          orderDetail={orderList[orderDetailIndexRef.current]}
          closePay={(update) => {
            setShowPay(false)
            if (update) {
              tabClick(current)
            }
          }}
        ></Payment>
      )}
      {/* 确认弹窗 */}
      <Modal
        title={modalInfo.title}
        content={modalInfo.content}
        cancelText='取消'
        confirmText='确定'
        onCancel={onCancel}
        onConfirm={onConfirm}
        isOpened={isOpened}
      ></Modal>
    </View>
  )
}

export default OrderLIst
